<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>转账 - 虚拟银行系统</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <link rel="stylesheet" href="/css/main.css">
  <style>
    /* Transfer page specific styles */
    .page-header {
      margin-bottom: var(--spacing-lg);
    }
    
    .page-title {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: var(--spacing-xs);
    }
    
    .page-subtitle {
      color: var(--light-text);
    }
    
    .transfer-wrapper {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: var(--spacing-xl);
    }
    
    .input-with-icon {
      position: relative;
    }
    
    .input-with-icon i {
      position: absolute;
      left: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: var(--light-text);
    }
    
    .input-with-icon input {
      padding-left: 40px;
    }
    
    .amount-input {
      position: relative;
    }
    
    .amount-input-prefix {
      position: absolute;
      left: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-color);
      font-weight: 500;
    }
    
    .amount-input input {
      padding-left: 30px;
    }
    
    .transfer-actions {
      margin-top: var(--spacing-lg);
      display: flex;
      justify-content: flex-end;
    }
    
    .recent-transfer-title {
      font-weight: 500;
      margin-bottom: var(--spacing-md);
    }
    
    .recent-transfer {
      padding: var(--spacing-md);
      background-color: white;
      border-radius: var(--border-radius-lg);
      margin-bottom: var(--spacing-md);
      cursor: pointer;
      display: flex;
      align-items: center;
      box-shadow: var(--card-shadow);
      transition: transform 0.3s;
    }
    
    .recent-transfer:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .recent-transfer-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: var(--bg-color);
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      color: white;
      margin-right: var(--spacing-md);
      flex-shrink: 0;
    }
    
    .recent-transfer-info {
      flex: 1;
    }
    
    .recent-transfer-name {
      font-weight: 500;
      margin-bottom: 4px;
    }
    
    .recent-transfer-account {
      font-size: 12px;
      color: var(--light-text);
    }
    
    .recent-transfer-amount {
      font-weight: 500;
      color: var(--error-color);
    }
    
    .transfer-tips {
      margin-top: var(--spacing-lg);
    }
    
    .transfer-tip {
      display: flex;
      align-items: flex-start;
      margin-bottom: var(--spacing-md);
    }
    
    .transfer-tip-icon {
      margin-right: var(--spacing-md);
      color: var(--accent-color);
      flex-shrink: 0;
    }
    
    /* Confirmation Modal */
    .confirmation-details {
      margin-bottom: var(--spacing-lg);
    }
    
    .confirmation-item {
      display: flex;
      margin-bottom: var(--spacing-md);
    }
    
    .confirmation-label {
      width: 100px;
      color: var(--light-text);
      flex-shrink: 0;
    }
    
    .confirmation-value {
      font-weight: 500;
    }
    
    .confirmation-amount {
      font-size: 24px;
      font-weight: 600;
      color: var(--primary-color);
      text-align: center;
      margin: var(--spacing-lg) 0;
    }
    
    /* Success Modal */
    .success-modal-icon {
      width: 80px;
      height: 80px;
      margin: 0 auto var(--spacing-lg);
      background-color: rgba(82, 196, 26, 0.1);
      color: var(--success-color);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40px;
    }
    
    .success-modal-title {
      text-align: center;
      font-size: 20px;
      font-weight: 600;
      margin-bottom: var(--spacing-md);
    }
    
    .success-modal-message {
      text-align: center;
      color: var(--light-text);
      margin-bottom: var(--spacing-lg);
    }
    
    .success-modal-actions {
      display: flex;
      justify-content: center;
    }
    
    /* Responsive */
    @media (max-width: 991px) {
      .transfer-wrapper {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
  <div class="app-wrapper">
    <!-- Top Navigation Bar -->
    <div id="top-navbar"></div>
    
    <div class="main-container">
      <!-- Sidebar -->
      <div id="sidebar"></div>
      
      <!-- Main Content -->
      <div class="content">
        <div class="page-header">
          <h1 class="page-title">转账</h1>
          <p class="page-subtitle">向他人转账或汇款</p>
        </div>
        
        <div class="transfer-wrapper">
          <!-- Transfer Form -->
          <div class="card">
            <div class="card-header">
              <h2 class="card-title">转账信息</h2>
            </div>
            <div class="card-body">
              <form id="transfer-form">
                <div class="form-group">
                  <label class="form-label" for="target-account">收款账号</label>
                  <div class="input-with-icon">
                    <i class="fas fa-user"></i>
                    <input type="text" id="target-account" name="targetAccount" class="form-control" placeholder="请输入收款人账号" required>
                  </div>
                  <div class="form-error" id="target-account-error"></div>
                </div>
                
                <div class="form-group">
                  <label class="form-label" for="transfer-amount">转账金额</label>
                  <div class="amount-input">
                    <span class="amount-input-prefix">¥</span>
                    <input type="number" id="transfer-amount" name="amount" class="form-control" placeholder="请输入转账金额" min="0.01" step="0.01" required>
                  </div>
                  <div class="form-error" id="amount-error"></div>
                </div>
                
                <div class="form-group">
                  <label class="form-label" for="transfer-remark">转账备注 (选填)</label>
                  <input type="text" id="transfer-remark" name="remark" class="form-control" placeholder="请输入转账备注" maxlength="50">
                </div>
                
                <div class="form-group">
                  <label class="form-label" for="transfer-password">支付密码</label>
                  <div class="input-with-icon">
                    <i class="fas fa-lock"></i>
                    <input type="password" id="transfer-password" name="password" class="form-control" placeholder="请输入支付密码" required>
                  </div>
                  <div class="form-error" id="password-error"></div>
                </div>
                
                <div class="transfer-actions">
                  <button type="button" class="btn btn-outline mr-2" id="cancel-btn">取消</button>
                  <button type="submit" class="btn btn-primary">确认转账</button>
                </div>
              </form>
            </div>
          </div>
          
          <!-- Recent Transfers & Tips -->
          <div>
            <!-- Recent Transfers -->
            <div class="recent-transfer-title">最近转账</div>
            <div id="recent-transfers-list">
              <div class="loader-container">
                <div class="loader"></div>
              </div>
            </div>
            
            <!-- Tips -->
            <div class="card mt-4">
              <div class="card-header">
                <h3 class="card-title">转账提示</h3>
              </div>
              <div class="card-body">
                <div class="transfer-tips">
                  <div class="transfer-tip">
                    <div class="transfer-tip-icon">
                      <i class="fas fa-info-circle"></i>
                    </div>
                    <div>转账前请确认收款方账号信息，避免填写错误。</div>
                  </div>
                  <div class="transfer-tip">
                    <div class="transfer-tip-icon">
                      <i class="fas fa-info-circle"></i>
                    </div>
                    <div>单笔转账限额为¥50,000，每日累计转账限额为¥200,000。</div>
                  </div>
                  <div class="transfer-tip">
                    <div class="transfer-tip-icon">
                      <i class="fas fa-info-circle"></i>
                    </div>
                    <div>转账成功后资金将实时到账，无法撤销，请谨慎操作。</div>
                  </div>
                  <div class="transfer-tip">
                    <div class="transfer-tip-icon">
                      <i class="fas fa-info-circle"></i>
                    </div>
                    <div>如有疑问，请联系客服：400-123-4567</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Confirmation Modal -->
    <div class="modal" id="confirmation-modal" style="display: none;">
      <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">确认转账</h3>
          <button class="modal-close" id="confirmation-close">&times;</button>
        </div>
        <div class="modal-body">
          <div class="confirmation-amount">¥<span id="confirm-amount">0.00</span></div>
          
          <div class="confirmation-details">
            <div class="confirmation-item">
              <div class="confirmation-label">收款账号</div>
              <div class="confirmation-value" id="confirm-account">-</div>
            </div>
            <div class="confirmation-item">
              <div class="confirmation-label">备注</div>
              <div class="confirmation-value" id="confirm-remark">-</div>
            </div>
          </div>
          
          <div class="alert alert-warning">
            <div class="alert-icon">
              <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div>转账后资金将实时到账，无法撤销，请确认信息无误</div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" id="back-btn">返回修改</button>
          <button class="btn btn-primary" id="confirm-transfer-btn">确认转账</button>
        </div>
      </div>
    </div>
    
    <!-- Success Modal -->
    <div class="modal" id="success-modal" style="display: none;">
      <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">交易结果</h3>
          <button class="modal-close" id="success-close">&times;</button>
        </div>
        <div class="modal-body">
          <div class="success-modal-icon">
            <i class="fas fa-check"></i>
          </div>
          <h3 class="success-modal-title">转账成功</h3>
          <p class="success-modal-message">您已成功转账 ¥<span id="success-amount">0.00</span> 给 <span id="success-account">-</span></p>
          <div class="success-modal-actions">
            <button class="btn btn-outline mr-2" id="view-details-btn">查看详情</button>
            <button class="btn btn-primary" id="new-transfer-btn">继续转账</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script src="/js/utils/Utils.js"></script>
  <script src="/js/components/Toast.js"></script>
  <script src="/js/services/ApiService.js"></script>
  <script src="/js/components/TopNavBar.js"></script>
  <script src="/js/components/SideBar.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Check if user is authenticated
      if (ApiService.redirectIfNotAuthenticated()) {
        return;
      }
      
      // Initialize components
      const topNavBar = new TopNavBar();
      topNavBar.init();
      
      const sideBar = new SideBar();
      sideBar.init('transfer');
      
      // Form elements
      const transferForm = document.getElementById('transfer-form');
      const targetAccountInput = document.getElementById('target-account');
      const amountInput = document.getElementById('transfer-amount');
      const remarkInput = document.getElementById('transfer-remark');
      const passwordInput = document.getElementById('transfer-password');
      
      // Error elements
      const targetAccountError = document.getElementById('target-account-error');
      const amountError = document.getElementById('amount-error');
      const passwordError = document.getElementById('password-error');
      
      // Modal elements
      const confirmationModal = document.getElementById('confirmation-modal');
      const successModal = document.getElementById('success-modal');
      const confirmAmount = document.getElementById('confirm-amount');
      const confirmAccount = document.getElementById('confirm-account');
      const confirmRemark = document.getElementById('confirm-remark');
      const successAmount = document.getElementById('success-amount');
      const successAccount = document.getElementById('success-account');
      
      // Buttons
      const cancelBtn = document.getElementById('cancel-btn');
      const confirmationCloseBtn = document.getElementById('confirmation-close');
      const backBtn = document.getElementById('back-btn');
      const confirmTransferBtn = document.getElementById('confirm-transfer-btn');
      const successCloseBtn = document.getElementById('success-close');
      const viewDetailsBtn = document.getElementById('view-details-btn');
      const newTransferBtn = document.getElementById('new-transfer-btn');
      
      // Load recent transfers
      loadRecentTransfers();
      
      // Form validation and submission
      transferForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
          showConfirmationModal();
        }
      });
      
      // Validate form
      function validateForm() {
        let isValid = true;
        
        // Reset errors
        targetAccountError.textContent = '';
        amountError.textContent = '';
        passwordError.textContent = '';
        
        // Validate target account
        if (!targetAccountInput.value.trim()) {
          targetAccountError.textContent = '请输入收款人账号';
          isValid = false;
        }
        
        // Validate amount
        if (!amountInput.value) {
          amountError.textContent = '请输入转账金额';
          isValid = false;
        } else {
          const amount = parseFloat(amountInput.value);
          if (isNaN(amount) || amount <= 0) {
            amountError.textContent = '请输入有效的转账金额';
            isValid = false;
          } else if (amount > 50000) {
            amountError.textContent = '单笔转账金额不能超过¥50,000';
            isValid = false;
          }
        }
        
        // Validate password
        if (!passwordInput.value) {
          passwordError.textContent = '请输入支付密码';
          isValid = false;
        }
        
        return isValid;
      }
      
      // Show confirmation modal
      function showConfirmationModal() {
        // Update confirmation details
        confirmAmount.textContent = parseFloat(amountInput.value).toFixed(2);
        confirmAccount.textContent = targetAccountInput.value.trim();
        confirmRemark.textContent = remarkInput.value.trim() || '无';
        
        // Show modal
        confirmationModal.style.display = 'flex';
      }
      
      // Hide confirmation modal
      function hideConfirmationModal() {
        confirmationModal.style.display = 'none';
      }
      
      // Show success modal
      function showSuccessModal(amount, account) {
        // Update success details
        successAmount.textContent = parseFloat(amount).toFixed(2);
        successAccount.textContent = account;
        
        // Show modal
        successModal.style.display = 'flex';
      }
      
      // Hide success modal
      function hideSuccessModal() {
        successModal.style.display = 'none';
      }
      
      // Load recent transfers
      function loadRecentTransfers() {
        const recentTransfersList = document.getElementById('recent-transfers-list');
        
        ApiService.get('/api/transaction/list', { tradeType: 3, page: 1, size: 5 })
          .then(response => {
            if (response.code === 0 && response.data) {
              const transactions = response.data.list || [];
              
              if (transactions.length === 0) {
                recentTransfersList.innerHTML = `
                  <div class="empty-state">
                    <p>暂无转账记录</p>
                  </div>
                `;
                return;
              }
              
              let html = '';
              transactions.forEach(transaction => {
                // Generate background color for avatar based on target account
                const bgColor = Utils.stringToColor(transaction.targetAccount);
                
                html += `
                  <div class="recent-transfer" data-account="${transaction.targetAccount}">
                    <div class="recent-transfer-avatar" style="background-color: ${bgColor}">
                      ${transaction.targetAccount.charAt(0).toUpperCase()}
                    </div>
                    <div class="recent-transfer-info">
                      <div class="recent-transfer-name">${transaction.targetAccount}</div>
                      <div class="recent-transfer-account">${Utils.formatDate(transaction.createTime)}</div>
                    </div>
                    <div class="recent-transfer-amount">-¥${transaction.amount.toFixed(2)}</div>
                  </div>
                `;
              });
              
              recentTransfersList.innerHTML = html;
              
              // Add click event to reuse recent transfer
              const recentTransfers = document.querySelectorAll('.recent-transfer');
              recentTransfers.forEach(item => {
                item.addEventListener('click', () => {
                  const account = item.getAttribute('data-account');
                  targetAccountInput.value = account;
                  
                  // Scroll to form and focus on amount input
                  transferForm.scrollIntoView({ behavior: 'smooth' });
                  amountInput.focus();
                });
              });
            }
          })
          .catch(error => {
            console.error('Error loading recent transfers:', error);
            recentTransfersList.innerHTML = `
              <div class="empty-state">
                <p>加载失败，请稍后再试</p>
              </div>
            `;
          });
      }
      
      // Execute transfer
      function executeTransfer() {
        // Show loading state
        confirmTransferBtn.disabled = true;
        confirmTransferBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        
        // Prepare transfer data
        const transferData = {
          targetAccount: targetAccountInput.value.trim(),
          amount: parseFloat(amountInput.value),
          remark: remarkInput.value.trim(),
          password: passwordInput.value
        };
        
        // Call transfer API
        ApiService.post('/api/account/transfer', transferData)
          .then(response => {
            // Reset button state
            confirmTransferBtn.disabled = false;
            confirmTransferBtn.textContent = '确认转账';
            
            if (response.code === 0) {
              // Hide confirmation modal
              hideConfirmationModal();
              
              // Show success modal
              showSuccessModal(transferData.amount, transferData.targetAccount);
              
              // Reset form
              transferForm.reset();
              
              // Reload recent transfers
              loadRecentTransfers();
            } else {
              Toast.error(response.message || '转账失败，请稍后再试');
            }
          })
          .catch(error => {
            // Reset button state
            confirmTransferBtn.disabled = false;
            confirmTransferBtn.textContent = '确认转账';
            
            console.error('Transfer error:', error);
            Toast.error('转账失败，请稍后再试');
          });
      }
      
      // Button event handlers
      cancelBtn.addEventListener('click', () => {
        window.location.href = '/index.html';
      });
      
      confirmationCloseBtn.addEventListener('click', hideConfirmationModal);
      
      backBtn.addEventListener('click', hideConfirmationModal);
      
      confirmTransferBtn.addEventListener('click', executeTransfer);
      
      successCloseBtn.addEventListener('click', hideSuccessModal);
      
      viewDetailsBtn.addEventListener('click', () => {
        hideSuccessModal();
        window.location.href = '/transactions.html';
      });
      
      newTransferBtn.addEventListener('click', () => {
        hideSuccessModal();
        // Reset form and focus on target account input
        transferForm.reset();
        targetAccountInput.focus();
      });
      
      // Close modals when clicking outside
      window.addEventListener('click', function(e) {
        if (e.target === confirmationModal) {
          hideConfirmationModal();
        } else if (e.target === successModal) {
          hideSuccessModal();
        }
      });
    });
  </script>
</body>
</html>
